﻿using System.Collections.Generic;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;

using System.Linq;


namespace EPiCloner
{
    public class Validator
    {
        private readonly Dictionary<PageData, PageData> _notValidItems = new Dictionary<PageData, PageData>();

        private Validator()
        {}

        public static Dictionary<PageData, PageData> Validate(PageReference currentPage)
        {
            var validator = new Validator();
            validator.ValidateRecursive(currentPage);
            return validator._notValidItems;
        }
        
        private void ValidateRecursive(PageReference currentPage)
        {
            var currentData = DataFactory.Instance.GetPage(currentPage);
            var currentType = PageType.Load(currentData.PageTypeID);
            var pageDataCollection = DataFactory.Instance.GetChildren(currentPage);
            if (pageDataCollection == null || pageDataCollection.Count == 0)
            {
                return;
            }

            foreach (var childPageData in pageDataCollection)
            {
                ValidateRecursive(childPageData.PageLink);

                if(currentType.AllowedPageTypes.Count() > 0 && !currentType.AllowedPageTypes.Contains(childPageData.PageTypeID))
                {
                    _notValidItems.Add(childPageData, currentData);
                }
            }
        }
    }
}